package com.glodon.paas.mail;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

public class SpringMailSenderExample {
	static SpringMailSender springMailSender;
	static JavaMailSender javaMailSender;
	
	// main
	public static void main(String[] args){
		// init
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:spring/testBeans-common-mail.xml");
		springMailSender = ctx.getBean(SpringMailSender.class);
		javaMailSender = ctx.getBean(JavaMailSender.class);
		
		// common
		SpringMailMessage mailMessage = new SpringMailMessage();	
		String[] array = new String[] { "huangc@grandsoft.com.cn","hch1011@163.com" };
		mailMessage.setTo(array);
		//mailMessage.setTo("hch1011@163.com");
		//mailMessage.setFrom(springMailSender.getDefaultFrom());
		
		// send

		Long startTiem = System.currentTimeMillis();
		//javaText(mailMessage);
		//springTemplate(mailMessage);
		springTemplateAsync(mailMessage);
		Long endTime = System.currentTimeMillis();
		System.err.println(" Consume time = " + (endTime - startTiem));
		System.err.println(" main() ok");
		
		ctx.destroy();
	}
	
	// Text java
	public static void javaText(SimpleMailMessage mailMessage) {		 
		mailMessage.setSubject("test:java text");
		mailMessage.setText("简单文本 ");
		
		javaMailSender.send(mailMessage);
		System.out.println(" javaText() ok ");
	}
	
	// Text spring
	public static void springText(SpringMailMessage mailMessage) {			
		mailMessage.setSubject("test:spring text");
		mailMessage.setText("简单文本spring发送");
		
		springMailSender.send(mailMessage);
		System.out.println(" springText() ok ");
	}
	
	// Template spring
	public static void springTemplate(SpringMailMessage mailMessage) {		
		mailMessage.setSubject("test:spring Template");
		mailMessage.setTemplateLocation("testMailTemplate/mailTemplate_hello.vm");
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("companyName", "广联达");
		model.put("link", "http://www.glodon.com/");
		model.put("userName", "测试用户");
		mailMessage.setTemplateParam(model);
		//mailMessage.setTextHtml(false);
		
		springMailSender.send(mailMessage);
		System.out.println(" springTemplate() ok ");
	}
	
	// Template spring
	public static void springTemplateAsync(SpringMailMessage mailMessage) {		
		mailMessage.setSubject("test:spring Template");
		mailMessage.setTemplateLocation("testMailTemplate/mailTemplate_hello.vm");
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("companyName", "广联达");
		model.put("link", "http://www.glodon.com/");
		model.put("userName", "测试用户");
		mailMessage.setTemplateParam(model);
		//mailMessage.setTextHtml(false);
		
		springMailSender.sendAsync(mailMessage);
		System.out.println(" springTemplate() ok ");
	}
}
